package com.dbq.fast.business.h5;

import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.dbq.fast.R;
import com.dbq.fast.common.base.BaseActivity;
import com.yiba.vpn.utils.Constants;
import com.yiba.vpn.utils.RxBus;

import butterknife.BindView;
import butterknife.ButterKnife;

public class H5ContainerActivity extends BaseActivity {

    public static final int WHICH_IS_PRIVACY = 0x01; //隐私条款
    public static final int WHICH_IS_HELP = 0x02; //使用帮助
    public static final int IS_HELP = 0x00; //使用帮助
    public static final int COMMON = 0x04; //使用帮助

    private static final String URL_PRIVACY = "http://www.shadows.rocks/miscellaneous/userAgreementPhone.html"; //用户协议
    private static final String URL_HELP = "http://www.shadows.rocks/miscellaneous/questionPhone.html"; //在线帮助
    private static final String USE_HELP = "http://www.shadows.rocks/miscellaneous/questionPhone.html?num=5"; //在线帮助
    @BindView(R.id.privacy_webview)
    WebView webView;

    @BindView(R.id.back2)
    ImageView back2;

    @BindView(R.id.progress_loading)
    ProgressBar progress_loading;
    @BindView(R.id.progress_text)
    TextView progress_text;
    @BindView(R.id.navi_bar)
    RelativeLayout rlBg;
    @BindView(R.id.textView)
    TextView tvTop;
    private String url = "";

    @BindView(R.id.frame_content)
    FrameLayout frameLayout;
    @BindView(R.id.title)
    TextView titleTV;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        try {
            setContentView(R.layout.activity_privacy);
            ButterKnife.bind(this);
            getFromWitch();
            initView();
        } catch (Exception e) {
        }
        back2.setOnClickListener((v) -> {
            this.finish();
        });
    }

    private void getFromWitch() {
        int whichOne = getIntent().getIntExtra("which", 1);
        switch (whichOne) {
            case IS_HELP:
                url = USE_HELP;
                titleTV.setText(getString(R.string.use_help));
                break;
            case 1:
                url = URL_PRIVACY;
                titleTV.setText(getString(R.string.privacy_item));
                break;
            case 2:
                url = URL_HELP;
                titleTV.setText(getString(R.string.use_help));
                break;
            case COMMON:

                url = getIntent().getStringExtra("url");
//                titleTV.setText(getIntent().getStringExtra("title"));
                rlBg.setVisibility(View.GONE);
                tvTop.setVisibility(View.GONE);
                back2.setVisibility(View.VISIBLE);
                break;
            default:
                url = URL_PRIVACY;
                titleTV.setText(getString(R.string.privacy_item));
                break;
        }
    }

    private void initView() {
        WebSettings webSettings = webView.getSettings();
        //设置自适应屏幕，两者合用
        webSettings.setUseWideViewPort(true); //将图片调整到适合webview的大小
        webSettings.setLoadWithOverviewMode(true); // 缩放至屏幕的大小
        webSettings.setJavaScriptEnabled(true);
        webSettings.setLoadsImagesAutomatically(true); //支持自动加载图片
//        webSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
        webSettings.setRenderPriority(WebSettings.RenderPriority.HIGH);
        webSettings.setBlockNetworkImage(true);
        webView.setLayerType(WebView.LAYER_TYPE_HARDWARE, null);//设置硬件加速
//        webView.setLayerType(WebView.LAYER_TYPE_SOFTWARE, null);//设置软件加速
        if (url.contains("?")) {
            webView.loadUrl(url + "&country=" + accessCountry());
        } else {
            webView.loadUrl(url + "?country=" + accessCountry());
        }
        webView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                progress_text.setText(newProgress + "%");
                //当内容加载完成以后，再去加载图片
                if (newProgress >= 100) {
                    webView.getSettings().setBlockNetworkImage(false);
                }
            }
        });
        webView.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                progress_loading.setVisibility(View.GONE);
                progress_text.setVisibility(View.GONE);
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
                progress_loading.setVisibility(View.VISIBLE);
                progress_text.setVisibility(View.VISIBLE);
            }

            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                super.onReceivedError(view, errorCode, description, failingUrl);
                progress_loading.setVisibility(View.GONE);
                progress_text.setVisibility(View.VISIBLE);
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                if (url.contains("http://www.baidu.com/")) {
                    RxBus.get().post(Constants.RXBUS_START_VPN, Constants.RXBUS_GO_WFEE);
                    H5ContainerActivity.this.finish();
                    return true;
                } else {
                    return false;
                }
            }

        });

        findViewById(R.id.back).setOnClickListener(view -> {
            onBackPressed();
        });
    }

    private String accessCountry() {
//        String language = SystemUtil.getLanguageCustom(App.getContext());
//        if(language == null) return "zh";
//        language = language.toLowerCase();
//        if("cn".equals(language)){
//            language = "zh";
//        }else if(language.contains("zh-") || language.contains("zh_")){
//            language = "zh";
//        }
//        return language;
        return "zh";
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (webView != null) {
            webView.onResume();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (webView != null) {
            webView.onPause();
        }
    }

    @Override
    protected void onDestroy() {
        if (webView != null) {
            //因为有传入了activity的context，所以要移除父容器，然后才能有效销毁
            frameLayout.removeView(webView);
            webView.destroy();
            webView = null;
        }
        super.onDestroy();
    }
}
